package com.cheyun.netsalev3.viewmodel

import android.content.Context
import android.content.Intent
import android.os.Looper
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Transformations
import com.cheyun.netsalev3.bean.IsPhoneParam
import com.cheyun.netsalev3.bean.MissedTellistParam
import com.cheyun.netsalev3.bean.PrivacyPhone
import com.cheyun.netsalev3.bean.login.PhoneX
import com.cheyun.netsalev3.repository.MissedTellistPageRepository
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.utils.ToastUtil
import com.cheyun.netsalev3.utils.api.ApiCallback
import com.cheyun.netsalev3.utils.api.ApiClient
import com.cheyun.netsalev3.utils.api.ApiException
import com.cheyun.netsalev3.utils.api.BaseResp
import com.cheyun.netsalev3.view.AddClueActivity
import com.cheyun.netsalev3.view.defeatdetails.DefeatDetailsActivity
import com.cheyun.netsalev3.widget.MyContentDialog
import com.dou361.dialogui.DialogUIUtils
import com.dou361.dialogui.listener.DialogUIItemListener
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

/**
 * @author Michael
 * @date  2018/12/12 - 11:22.
 */
class MissedTelActivityViewModel(var missedTelActivityRepository: MissedTellistPageRepository) : BaseViewModel() {

    var listdata = missedTelActivityRepository.loadAndroidData()
    var networkState= Transformations.switchMap(listdata){
        missedTelActivityRepository.networkState
    }!!


    /**
     * 刷新
     */
    fun refresh() {
        missedTelActivityRepository.dataSourceFactory.sourceLiveData.value?.invalidate()
    }

    fun onClick(view:View,item:MissedTellistParam){
        if(item.archive == 0){
            var intent = Intent(view.context, AddClueActivity::class.java)
            intent.putExtra("phone", item.phone)
            view.context.startActivity(intent)
        }else{
            getPhone(item.phone)
//            if(item.tid.isNullOrEmpty()){
//
//            }else{
//                var intent = Intent(view.context, DefeatDetailsActivity::class.java)
//                intent.putExtra("tid", item.tid)
//                intent.putExtra("nkey", "archive.index")
//                view.context.startActivity(intent)
//            }
        }
    }
    fun onMsgClick(view:View,item:MissedTellistParam){
        FunctionUtils.sendSMSTo(view.context, item.phone, "")
    }

    fun setPhoneList(phoneList: List<PhoneX>) {
        val strings = ArrayList<String>()
        phoneList.forEach{strings.add("["+it.supusename+"]" + it.phonex)}
        if(phoneList.size>0){
            Looper.prepare()
            DialogUIUtils.showBottomSheetAndCancel(mContext,strings,"取消",object: DialogUIItemListener(){
                override fun onItemClick(text: CharSequence, position: Int) {
                    var current = phoneList.get(position)
                    if(current.phonex.equals(MySharedPreferences.getMobile())){
                        FunctionUtils.callPhone(mContext!!, currentItem?.phone!!)
                    }else{
                        var enableBenji:Boolean = false
                        if(currentItem?.phone!!.indexOf("*")==-1){
                            enableBenji = true
                        }
                        getPrivacyPhone(current.phonex!!,if(enableBenji) currentItem?.phone!! else "",if(enableBenji) "" else currentItem?.tid!!, this@MissedTelActivityViewModel::setPrivacyPhone)
                    }
                }
            }).show()
            Looper.loop()
        }else{
            ToastUtil.toastShortMessage("无工作号，暂时无法呼叫")
        }
    }
    private var currentItem:MissedTellistParam? = null

    fun onTelClick(view: View, item:MissedTellistParam) {
        mContext = view.context
        currentItem = item
        getOwnerPhone(item.phone,this@MissedTelActivityViewModel::setPhoneList);
    }

    var mContext: Context? = null
    fun setPrivacyPhone(s: String) {
        FunctionUtils.callPhone(mContext!!, s)
    }

    fun getPrivacyPhone(phonex:String,phoneb:String,tid:String, moth: (s:String) -> Unit){
        ApiClient.getInstance().getPrivacyPhone(phonex,phoneb,tid)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        object : ApiCallback<BaseResp<PrivacyPhone>>() {
                            override fun onSuccess(t: BaseResp<PrivacyPhone>) {
                                moth(t.data?.phonex!!)
                            }

                            override fun onError(ex: ApiException) {

                            }

                        })
    }

    fun getOwnerPhone(phoneB: String, moth: (List<PhoneX>) -> Unit) {
        ApiClient.getInstance().getPhoneList(phoneB)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        object : ApiCallback<BaseResp<List<PhoneX>>>() {
                            override fun onSuccess(t: BaseResp<List<PhoneX>>) {
                                moth(t.data!!)
                            }

                            override fun onError(ex: ApiException) {

                            }

                        })
    }

    var isPhoneParam: IsPhoneParam? = null
    var activity: AppCompatActivity? = null
    /**
     * 检查电话号码是否存在
     */
    fun getPhone(phone: String) {
        isPhoneParam = null
        var moth: (item: IsPhoneParam) -> Unit = {
            if (it.state == "n") {
                var show = true
                if (it != null && !it!!.revkey.isNullOrEmpty()) {
//                    if(it!!.revkey.equals("bazaar") || it!!.revkey.equals("owner")|| it!!.revkey.equals("check")){
//                        show = false
//                        MyToast(it!!.msg)
//                    }
                    //2020-04-22  线索从线索池导入后，如果线索在“审核管理”模块，同“战败管理”线索处理机制一样激活，重新分配
                    if(it!!.revkey.equals("bazaar") || it!!.revkey.equals("owner")){
                        show = false
                        MyToast(it!!.msg)
                    }
                }
                if(show) {
                    isPhoneParam = it
                    showPop()
                }
            }

        }
        missedTelActivityRepository.IsPhone(phone, moth)
    }

    /**
     *显示弹窗
     */
    fun showPop() {
        isPhoneParam?.apply {
            activity?.apply {
                var dialog = MyContentDialog.newInstance("提示", isPhoneParam!!.msg)
                dialog.onClickOk = this@MissedTelActivityViewModel::onClickOk
                dialog.show( this.supportFragmentManager, "")
            }
        }
    }

    /**
     * 点击弹窗ok
     */
    fun onClickOk() {
        activity?.apply {
            if (isPhoneParam != null && !isPhoneParam!!.revkey.isNullOrEmpty()) {
                var intent = Intent(this, DefeatDetailsActivity::class.java)

                if(isPhoneParam!!.tid.isNullOrEmpty()){
                    intent.putExtra("revkey", isPhoneParam!!.revkey)
                }else {
                    intent.putExtra("tid", isPhoneParam!!.tid)
                }

                if(isPhoneParam!!.revkey.equals("follow") || isPhoneParam!!.revkey.equals("followtip")){
                    intent.putExtra("nkey", "archive.purge")  // 跟进，订车，线索移交
                }else{
                    intent.putExtra("nkey", "archive.index")
//                    intent.putExtra("nkey", "archivepot.index")  // 拨号，激活
                    intent.putExtra("revkey", isPhoneParam!!.revkey)
                }

                intent.putExtra("come", "")
                this.startActivity(intent)
            }
        }
    }
}